// pages/index/panel/cctPanel/cctPanel.js

// import Area
const app = getApp()
const cloud = require('../../../../utils/cloudFunction')
const con = require('../../../../utils/control')


// value
var startPoint;
// var date = new Date()
const hours = []
const minutes = []

// calc js
for (let index = 0; index < 18; index++) {
    hours.push(index)
}
for (let index = 0; index < 60; index++) {
    minutes.push(index)
}

Page({

    /**
     * Page initial data
     */
    data: {
        clock: '',
        isDev: true,
        // hardware variable
        runStatus: false,
        lamp: false,
        brightness: 50,
        tmpBrightness: 50, // 临时亮度
        cw: 50,

        // room & device info
        devId: 0,
        devName: '',
        devMac: 0,
        roomId: 0,
        roomName: '',
        roomMac: 0,
        // roomList: [],
        // cctDeviceId: 0,
        // cctDeviceName: "",
        // cctRoomId: 0,

        // color dish 
        degress: 0,
        radius: 0,
        dishShow: false,
        dishWidth: '100px',

        // brightnessBtn
        calcStatus: false,
        hiddenMask: true,
        btnActive: false,
        btnHeight: "32px",
        btnTouchStatus: false,
        btnProportion: 1.6,
        btnPercent: "50%",
        startY: 0,
        topY: 0,
        bottomY: 0,
        leftX: 0,
        rightX: 0,

        // presetBtn
        presetList: [{
            name: 'timer',
            presetBackground: '#343434',
            icon: '/image/icon/countdown.png'
        },
        {
            name: '1stDIY',
            presetBackground: '#343434',
            info: 'DIY',
            brightnessValue: 0,
            cwValue: 0
        },
        {
            name: '2ndDIY',
            presetBackground: '#343434',
            info: 'DIY',
            brightnessValue: 0,
            cwValue: 0
        },
        {
            name: '3rdDIY',
            presetBackground: '#343434',
            info: 'DIY',
            brightnessValue: 0,
            cwValue: 0
        },
        {
            name: 'warmWhite',
            presetBackground: '#343434',
            icon: '/image/icon/brightness_w.png'
        },
        {
            name: 'natureWhite',
            presetBackground: '#343434',
            icon: '/image/icon/brightness_n.png'
        },
        {
            name: 'coolWhite',
            presetBackground: '#343434',
            icon: '/image/icon/brightness_c.png'
        },
        {
            name: 'nightMode',
            presetBackground: '#343434',
            icon: '/image/icon/brightness_b.png'
        },
        ],

        // timeType
        animationData: {},
        showInfoFlag: 0,
        hiddenDialog: true,
        timeHours: hours,
        timeMinutes: minutes,
        hour: 0,
        minute: 0,
        timePickerValue: [0, 0],
        timeTypeList: [
            { type: "delayer", name: "慢慢关" },
            { type: "timer", name: "延时关" },
            { type: "planner", name: "计划任务" },
        ],
        delayValue: [
            { name: "10秒", seconds: 10, },
            { name: "30秒", seconds: 30, },
            { name: "2分钟", seconds: 120, },
            { name: "5分钟", seconds: 300, },
            { name: "10分钟", seconds: 600, },
            { name: "1小时", seconds: 3600, },
        ]

    },

    /**
     * Lifecycle function--Called when page load
     */
    onLoad(options) {
        // var that = this
        this.ifDev(options)
        this.initPresetList()
    },

    /**
     * Lifecycle function--Called when page is initially rendered
     */
    onReady() {

        // draw dish components
        setTimeout(() => {
            var q = wx.createSelectorQuery();
            q.select(".dishArea").boundingClientRect(rect => {
                // console.log(rect)
                var tmp;
                if (rect.width >= rect.height) {
                    tmp = rect.height
                } else {
                    tmp = rect.width
                }
                this.setData({
                    dishWidth: tmp * 0.8 + 'px',
                    dishShow: true
                })

            }).exec();

            // 设备页面命名
            this.setPanelTitle(this.data.devName);
        }, 100);

    },

    /**
     * Lifecycle function--Called when page show
     */
    onShow() {
        // 循环刷新灯的状态
        // this.data.clock = setInterval(() => {
        // console.log("Mac ... ", this.data.devAddress, this.data.roomAddress)
        // }, 2000);

    },

    /**
     * Lifecycle function--Called when page hide
     */
    onHide() {

    },

    /**
     * Lifecycle function--Called when page unload
     */
    onUnload() {

        clearInterval(this.data.clock)
    },

    /**
     * Page event handler function--Called when user drop down
     */
    onPullDownRefresh() {

    },

    /**
     * Called when page reach bottom
     */
    onReachBottom() {

    },

    /**
     * Called when user click on the top right corner to share
     */
    onShareAppMessage() {

    },

    //======================================= 页面初始配置

    /**
     * 通过其他页面传值，判断是控制房间还是设备
     * @param {object} options 其他页面传值
     */
    ifDev(options) {
        // console.log(options)
        var light = JSON.parse(options.lampStatus)
        if (options.isDev) {
            // 进入设备控制页
            if (light) {
                // 设备info setdata
                this.setData({
                    lamp: true,
                    brightness: light,
                    btnPercent: light + "%",
                    devId: options.devId,
                    devMac: options.devMac,
                    devName: options.title,
                    roomId: options.roomId,
                    roomMac: options.roomMac,
                })
            } else {
                // 设备info setdata
                this.setData({
                    lamp: false,
                    brightness: 0,
                    btnPercent: "0%",
                    devId: options.devId,
                    devMac: options.devMac,
                    devName: options.title,
                    roomId: options.roomId,
                    roomMac: options.roomMac,
                })
            }
        } else {
            // 进入房间控制页
            this.setData({
                isDev: false,
                lamp: true,
                brightness: light,
                btnPercent: light + "%",
                devName: options.title,
                roomId: options.roomId,
                roomMac: options.roomMac,
            })
        }
    },

    initPresetList() {
        var preset = wx.getStorageSync('cachePreset')
        console.log(preset)
        // read preset if defined
        if (preset) {
            try {
                var p1 = 'presetList[1]'
                var p2 = 'presetList[2]'
                var p3 = 'presetList[3]'
                // console.log(p1)
                this.setData({
                    [p1]: preset[0],
                    [p2]: preset[1],
                    [p3]: preset[2],
                })
            } catch (e) {
                console.log("read preset if defined", e)
            }
        }
    },

    // ================================================== 渲染层相关 ==========================


    pairDev() {
        con.pairDev(this.data.devMac, this.data.roomMac)
    },

    /**
         * 开关状态监听，控制灯开关，适配预设按钮和亮度滑块的联动
         */
    listenerSwitch(e) {
        // console.log('switch类型开关当前状态-----', e.detail.value);
        if (e.detail.value == true) {
            // 开关打开 => turnOn 同时，保留临时亮度
            this.controlBrightness(1, this.data.tmpBrightness)
        } else {
            // 开关关闭 => turnOff 同时，清除预设按钮背景，保留临时亮度
            this.resetPresetBackground()
            this.controlBrightness(0, 0)
        }
        // this.lampBtnFresh()
    },
    /**
     * 开关switch 与 灯开关状态同步
     */
    lampBtnFresh() {
        // if (this.data.runStatus) {
        // console.log("lampBtnFresh*******")
        // } else return
        if (this.data.brightness > 0) {
            this.setData({
                lamp: true
            })
        } else {
            this.setData({
                lamp: false
            })
        }
    },


    /**
     * dish 开始
     */
    choseCWStart() {
        // 重置预设按钮背景
        this.resetPresetBackground()
        if (!this.data.lamp) {
            // 灯是关的, turn on first
            this.controlBrightness(1, this.data.tmpBrightness)
        }
        console.log("choseCWStart")
    },

    /**
     * 色盘对应的方法：选择色温数值，并调色温
     * 定时器延时
     */
    choseCW(e) {
        setTimeout(() => {
            this.data.cw = 99 - e.detail.color
            con.setFull(this.choseMac(), this.data.cw, this.data.brightness)
            console.log("choseCW ok")
        }, 800);
    },

    /**
     * dish 结束
     */
    choseCWEnd() {
        console.log("choseCWEnd")
        if (this.data.isDev) {
            cloud.devControl(this.choseId(), this.data.cw, this.data.brightness)
        } else {
            cloud.roomControl(this.choseId(), this.data.cw, this.data.brightness)
        }
    },

    /**
     * 亮度滑块高度切换
     */
    swHeight() {
        // var Status = !this.data.btnActive
        // 按钮激活 => 失效 
        if (this.data.btnActive) {
            this.setData({
                btnHeight: "32px",
                hiddenMask: true,
                btnActive: false,
                btnTouchStatus: false,
            })
        } else {
            // 按钮失效 => 激活
            this.setData({
                btnHeight: "160px",
                hiddenMask: false,
                btnActive: true,
                btnTouchStatus: true,
            })
        }
    },
    /**
     * calculatePrecnet 计算亮度滑块 背景色百分比
     */
    calculatePrecnet(newY) {
        // 判断是否在范围内
        switch (true) {
            case newY < this.data.topY:
                return 100

            case newY >= this.data.topY && newY <= this.data.bottomY:
                return Math.ceil((this.data.bottomY - newY) / this.data.btnProportion)

            case newY > this.data.bottomY:
                return 0

            default:
                break;
        }
    },
    /**
     * brightness slider - choseBrightnessStart
     */
    choseBrightnessStart(e) {
        // 清除预设按钮背景
        this.resetPresetBackground()
        if (!this.data.btnTouchStatus) {
            return
        } else {
            // 判断是否运行过计算元素高度范围
            if (!this.data.calcStatus) {
                this.setData({
                    topY: e.currentTarget.offsetTop,
                    bottomY: e.currentTarget.offsetTop + 160,
                    leftX: e.currentTarget.offsetLeft,
                    rightX: e.currentTarget.offsetLeft + 32,
                    calcStatus: true
                })
            }
            var value = this.calculatePrecnet(e.touches[0].pageY)

            // setBrightness
            this.setData({
                brightness: value,
                btnPercent: value + '%'
            })
            con.setBrightness(this.choseMac(), value)

            // 更新lamp - switch
            this.lampBtnFresh()
            // con.setBrightness(this.data.value, this.choseMac())
        }
    },
    /**
     * choseBrightnessMove
     */
    choseBrightnessMove(e) {
        if (!this.data.btnTouchStatus) {
            return
        } else {
            setTimeout(() => {
                var value = this.calculatePrecnet(e.touches[0].pageY)
                // setBrightness
                this.setData({
                    brightness: value,
                    btnPercent: value + '%'
                })
                con.setBrightness(this.choseMac(), value)

                // 更新lamp - switch
                this.lampBtnFresh()
            }, 800);
        }
    },

    /**
     * choseBrightnessEnd
     */
    choseBrightnessEnd(e) {
        // console.log(e)
        if (!this.data.btnTouchStatus) {
            return
        } else {
            var value = this.data.brightness
            if (this.data.isDev) {
                cloud.devControl(this.choseId(), null, value)
            } else {
                cloud.roomControl(this.choseId(), null, value)
            }
            setTimeout(() => {
                // 收起滑动条
                this.setData({
                    btnHeight: "32px",
                    hiddenMask: true,
                    btnActive: false,
                    btnTouchStatus: false,
                })
                // 更新lamp - switch
                this.lampBtnFresh()
            }, 200);
            console.log("set brightness end")
        }
    },

    controlBrightness(type, value) {
        switch (type) {
            case 0: // turnoff
                con.turnOff(this.choseMac())
                this.setData({
                    lamp: false,
                    tmpBrightness: this.data.brightness,
                    brightness: value,  // 0
                    btnPercent: "0%"
                })
                break;
            case 1: // turnon
                this.setData({
                    lamp: true,
                    brightness: this.data.tmpBrightness,
                    btnPercent: this.data.tmpBrightness + "%"
                })
                con.turnOn(this.choseMac())
                break;
            case 2:
                break;

            default:
                break;
        }
        if (this.data.isDev) {
            cloud.devControl(this.choseId(), null, value)
        } else {
            cloud.roomControl(this.choseId(), null, value)
        }
    },

    /**
     * 预设按钮对应方法
     */
    presetControl(e) {
        // console.log("id", e.currentTarget)
        console.log("index: " + e.currentTarget.dataset.index)
        var data = e.currentTarget.dataset.index
        switch (e.currentTarget.id) {
            case "timer":
                this.changeOptionsAnimation()
                // this.showModal()
                // console.log(e.currentTarget.dataset.index)
                // this.resetPresetBackground()
                // wx.showToast({
                //     title: '功能完善中',
                //     icon: 'error',
                //     duration: 1500
                // })
                break;

            case "1stDIY":
            // console.log(this.data.presetList[data].info, this.data.presetList[data].cwValue, this.data.presetList[data].brightnessValue)

            // break;

            case "2ndDIY":

            // break;

            case "3rdDIY":
                this.resetPresetBackground()

                var diyInfo = this.data.presetList[data].info
                var diyCW = this.data.presetList[data].cwValue
                var diyBri = this.data.presetList[data].brightnessValue
                if (diyInfo == 'DIY') {
                    this.errorToast('长按保存状态')
                } else (
                    this.diyControl(diyCW, diyBri)
                )

                break;

            case "warmWhite":
                // console.log(data)
                this.resetPresetBackground(data)
                // 设置暖色 50亮度
                this.diyControl(0, 50)


                break;

            case "natureWhite":
                // console.log(data)
                this.resetPresetBackground(data)
                // 设置自然色 50亮度
                this.diyControl(50, 50)

                break;

            case "coolWhite":
                // console.log(data)
                this.resetPresetBackground(data)
                // 设置冷色 50亮度
                this.diyControl(100, 50)

                break;

            case "nightMode":
                // console.log(data)
                this.resetPresetBackground(data)
                // 设置自然色 最暗
                this.diyControl(50, 1)

                break;

            default:
                break;
        }
    },

    errorToast(info) {
        wx.showToast({
            title: info,
            icon: 'error',
            duration: 1500
        })
    },

    diyControl(cw, bri) {
        con.setFull(this.choseMac(), cw, bri)
        this.setData({
            cw: cw,
            brightness: bri,
            btnPercent: bri + "%"
        })
        if (this.data.isDev) {
            // dev
            cloud.devControl(this.choseId(), cw, bri)
        } else {
            cloud.roomControl(this.choseId(), cw, bri)
        }
        this.lampBtnFresh()
    },

    /**
     * 改变按钮背景色，id 为按钮字符
     * @param {String} id 
     */
    resetPresetBackground(id) {
        // 清空所有按钮背景，调用即执行
        for (let i = 4; i < this.data.presetList.length; i++) {
            let tmp = 'presetList[' + i + '].presetBackground'
            this.setData({
                [tmp]: "#343434",
            })
        }
        // 重新更新id对应按钮的背景，无参传入不执行
        if (id != null) {
            let tmpColor = 'presetList[' + id + '].presetBackground'
            this.setData({
                [tmpColor]: "#03A9F4",
            })
        }
    },

    /**
     * 自定义预设保存
     */
    saveDIY(e) {
        var index = e.currentTarget.dataset.index
        if (index > 0 && index < 4) {
            var presetBG = 'presetList[' + index + '].presetBackground'
            var presetINFO = 'presetList[' + index + '].info'
            var presetCW = 'presetList[' + index + '].cwValue'
            var presetBN = 'presetList[' + index + '].brightnessValue'
            var cwColor = ''
            var tmpCW = this.data.cw
            // cwColor = 'rgb(254,143,41)' // - 0
            // cwColor = 'rgb(255,238,221)' // - 50
            // cwColor = 'rgb(211,220,248)' // - 100
            console.log('LONG PRESS ... ', index)
            switch (true) {
                // cw = 0 对应暖色
                case tmpCW >= 0 && tmpCW < 50:
                    // console.log('0', cwColor)
                    // cwColor = 'rgb(254,143,41)' // - 0
                    var r = 254 + Math.ceil(tmpCW / 49)
                    var g = 143 + Math.ceil(tmpCW * (95 / 49))
                    var b = 41 + Math.ceil(tmpCW * (180 / 49))
                    cwColor = 'rgb(' + r + ',' + g + ',' + b + ')'

                    break;

                // cw = 100 对应冷色
                case tmpCW > 50 && tmpCW <= 100:
                    // console.log('100', cwColor)
                    // cwColor = 'rgb(211,220,248)' // - 100
                    var r = 255 - Math.ceil((tmpCW - 50) * (44 / 49))
                    var g = 238 - Math.ceil((tmpCW - 50) * (18 / 49))
                    var b = 221 + Math.ceil((tmpCW - 50) * (27 / 49))
                    cwColor = 'rgb(' + r + ',' + g + ',' + b + ')'

                    break;

                default:
                    // console.log('50', cwColor)
                    cwColor = 'rgb(255,238,221)' // - 50
                    break;
            }
            this.setData({
                [presetBG]: cwColor,
                [presetINFO]: this.data.brightness + '%',
                [presetCW]: this.data.cw,
                [presetBN]: this.data.brightness
            })

            // save preset list 
            setTimeout(() => {
                let tmpP = []
                for (let i = 0; i < 3; i++) {
                    tmpP.push(this.data.presetList[i + 1])
                }
                wx.setStorageSync('cachePreset', tmpP)
            }, 200);
        }

    },

    /**
     * cct 页面触摸就触发
     * 判断首次打开页面的点击事件，用作开关刷新根据
     */
    run() {
        // console.log("--")
        if (!this.data.runStatus) {
            this.data.runStatus = true
        }
    },
    /**
     * closeMask
     */
    closeMask() {
        this.setData({
            btnHeight: "32px",
            hiddenMask: true,
            btnActive: false,
            btnTouchStatus: false,
        })
    },
    /**
     * setNavigationBarTitle 修改页面标题
     */
    setPanelTitle(name) {
        wx.setNavigationBarTitle({
            title: name
        })
    },

    /**
     * 底部选项卡的状态切换 滑入 滑出动画
     * @param {Number} inFlag 可选，更改所选标志位 后 滑入
     * @param {Number} outFlag 可选，滑出 后 更改为所选标志位后
     */
    changeOptionsAnimation(inFlag, outFlag) {
        if (inFlag != null) {
            this.setData({
                showInfoFlag: inFlag
            })
        }
        // animation
        var animation = wx.createAnimation({
            duration: 300,//动画的持续时间 默认400ms
            timingFunction: 'ease',//动画的效果 默认值是linear
        })
        this.animation = animation
        if (this.data.hiddenDialog) {
            // hiddenDialog true => false flyin
            this.setData({
                hiddenDialog: false
            })
            //调用动画--滑入
            var t = setTimeout(() => {
                this.animation.translateY(0).step() // 在y轴偏移，然后用step()完成一个动画
                this.setData({
                    //动画实例的export方法导出动画数据传递给组件的animation属性
                    animationData: this.animation.export()
                })
                clearTimeout(t)
            }, 100);
        } else {
            // hiddenDialog flase => true flyout
            this.animation.translateY(200).step()
            this.setData({
                animationData: this.animation.export(),
            })
            var t = setTimeout(() => {
                this.setData({
                    hiddenDialog: true
                })
                clearTimeout(t);
            }, 220);//先执行下滑动画，再隐藏模块

        }
        setTimeout(() => {
            if (outFlag != null) {
                this.setData({
                    showInfoFlag: outFlag
                })
            }
        }, 300);
    },

    /**
     * 子选项的对应动作
     * @param {obj} e 点击事件 - event对象
     */
    choseType(e) {
        // console.log(e)
        if (this.data.lamp == false) {
            this.errorToast('请先打开灯')
            return
        }
        switch (e.currentTarget.dataset.type) {
            case "delayer":
                this.changeOptionsAnimation()
                setTimeout(() => {
                    this.changeOptionsAnimation(1, null)
                }, 300);
                break;

            case "timer":
                this.changeOptionsAnimation()
                setTimeout(() => {
                    this.changeOptionsAnimation(2, null)
                }, 300);
                break;

            case "planner":
                this.changeOptionsAnimation()
                setTimeout(() => {
                    this.changeOptionsAnimation(3, null)
                }, 300);
                break;

            default:
                break;
        }
    },

    /**
     * 取消选项卡的显示
     */
    cancelOption() {
        this.changeOptionsAnimation(null, 0)
    },

    /**
     * 应用 慢慢关
     */
    applyDelayer(e) {
        this.changeOptionsAnimation(null, 0)
        var ms = e.currentTarget.dataset.value * 10
        con.offDelayer(this.choseMac(), ms)
    },

    /**
     * picker 选择时间并赋值给 hour minute
     */
    pickTime(e) {
        var val = e.detail.value
        this.setData({
            hour: this.data.timeHours[val[0]],
            minute: this.data.timeMinutes[val[1]],
        })
    },

    /**
     * 应用 延时关
     */
    applyTimer() {
        if (this.data.hour == 0 && this.data.minute == 0) {
            wx.showToast({
                title: '请先选择时间',
                icon: 'error',
                duration: 1500
            })
        } else {
            this.changeOptionsAnimation(null, 0)
            var s = this.data.hour * 3600 + this.data.minute * 60

            con.offTimer(this.choseMac(), s)
        }
    },

    /**
     * 控制之前，判断是控制房间还是控制设备，返回mac
     */
    choseMac() {
        if (this.data.isDev) {
            return this.data.devMac
        } else {
            return this.data.roomMac
        }
    },

    /**
     * 控制之前，判断是控制房间还是控制设备，返回Id
     */
    choseId() {
        if (this.data.isDev) {
            return this.data.devId
        } else {
            return this.data.roomId
        }
    }


})